package com.flexcloudsdk.web;

import java.io.IOException;

import java.io.PrintWriter;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CloudFetchServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final Logger log = Logger.getLogger(CloudFetchServlet.class
			.getName());
	private String sourceMethod;
	private String sourceClass;

	public CloudFetchServlet() {
		sourceMethod = Thread.currentThread().getStackTrace()[1].getMethodName().toString();
		sourceClass = CloudFetchServlet.class.getName();
		log.info("*****CloudFetchServlet constructor********");
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		sourceMethod = Thread.currentThread().getStackTrace()[1].getMethodName().toString();
		log.info("Executing: " + sourceClass + "." + sourceMethod);
	
		resp.setContentType("text/xml");
		PrintWriter writer = resp.getWriter();
		writer.println("<?xml version=\"1.0\"?>");
		writer.println("<root>");

		String operation = req.getParameter("operation");
		if (operation == null) {
			handleNullOperation(writer, req);
		} else if (operation.isEmpty()) {
			handleEmptyOperation(writer, req);
		}
		writer.println("</root>");

		log.exiting(sourceClass, sourceMethod);
	}

	private void handleNullOperation(PrintWriter writer, HttpServletRequest req) {
		sourceMethod = Thread.currentThread().getStackTrace()[1].getMethodName().toString();
		log.info("Executing: " + sourceClass + "." + sourceMethod);
		log.warning("operation is null");
		writer.println("<result>No operation found while calling "
				+ req.getServerName() + "servlet</result>");
	}

	private void handleEmptyOperation(PrintWriter writer, HttpServletRequest req) {
		sourceMethod = Thread.currentThread().getStackTrace()[1].getMethodName().toString();
		log.info("Executing: " + sourceClass + "." + sourceMethod);
		log.warning("operation is empty");
		writer.println("<result>Must pass an operation in calling "
				+ req.getServerName() + "servlet</result>");
	}

}
